package view
{
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.setTimeout;
	
	import models.ModelLocator;

	public class UploadImg
	{
		public var uploadAlert:UploadAlert = new UploadAlert;
		private var upList:Array;
		private var flag:int;
		private var key:String;
		public function UploadImg(parent:DisplayObjectContainer)
		{
			parent.addChild(uploadAlert);
			uploadAlert.x = 200;
			uploadAlert.y = 200;
			//uploadAlert.setProgress(0.5);
			//uploadAlert.setInfo("正在处理正面图片...");
		}
		
		public function upLoad(ary:Array,key:String):void{
			this.upList = ary;
			flag = 0;
			this.key = key;
			if(ary.length == 1){
				up(true);
			}else{
				up(false);
			}
			
		}
		private function up(isEnd:Boolean=false):void{
			var obj:Object = upList[flag]
			var urlloader:URLLoader = new URLLoader();
			var url:String;
			if(isEnd){
				url = ModelLocator.getInstance().submitPreview + '&mark=' + obj.mark + "&id=" + this.key + "&tag=end"; 
			}else{
				url = ModelLocator.getInstance().submitPreview + '&mark=' + obj.mark + "&id=" + this.key; 
			}
			// ModelLocator.getInstance().config.submit + "?size=" + model.size + "&type=" + sendID;
			var urlreq:URLRequest = new URLRequest(url)
			urlreq.data = obj.byte;
			urlreq.method = URLRequestMethod.POST;  
			urlreq.contentType = "application/octet-stream";  
			urlloader.addEventListener(Event.COMPLETE,com);
			urlloader.addEventListener(IOErrorEvent.IO_ERROR,ioError);
			urlloader.load(urlreq);
			uploadAlert.setInfo("正在处理" + obj.name + "图片...");
		}
		private function com(evnet:Event):void{
			if(evnet.target.data == "2"){
				ExternalInterface.call("go");
			}
			flag++;
			uploadAlert.setProgress(flag/upList.length);
			if(flag == upList.length){
				return;
			}
			if(flag == upList.length-1){
				up(true);
			}else{
				up(false);
			}
			
		}
		private function ioError(event:IOErrorEvent):void{
			flag++;
			uploadAlert.setProgress(flag/upList.length);
			if(flag == upList.length){
				return;
			}
			setTimeout(up,2000);
			//up();
		}
		
		
	}
}